package org.bunny.vehicle.service;

import org.bunny.vehicle.entity.User;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.bunny.vehicle.util.Utils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class CommonService extends BaseService {

	public boolean login(String json) {
		JSONObject obj = JSON.parseObject(json);

		String number = JSON.getString(obj, "number");
		String password = JSON.getString(obj, "password");

		if (!Utils.isEmpty(number, password)) {
			User user = userRepository.findByNumber(number);
			if (null != user && password.equals(user.getPassword())) {
				setSessionAttribute(Const.SESSION_USER, user);
				try {
					JSONArray array = obj.getJSONArray("remember");
					if (array.size() > 0) {
						setCookie(Const.COOKIE_USER, user, Const.MAX_AGE);
					}
				} catch (Exception e) {
					log.error(e + json, e);
				}
				return true;
			}
		}
		return false;
	}

	public boolean logout() {
		setSessionAttribute(Const.SESSION_USER, null);
		setCookie(Const.COOKIE_USER, null, 0);
		return true;
	}

}
